<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="myScript.js"></script>
</head>
<body>
<h1>对象</h1>
<input type="text" id="str"/>
<p id="print">aaa</p>
<p id="getset"></p>
<p id="construct"></p>
<p id="x"></p>
<button value="Submit" onclick="person.action('Hello JS!')">请点我</button>
<button value="Submit" onclick="fun()">打印Person</button>
<button value="Submit" onclick="add()">添加Person属性</button>
<button value="Submit" onclick="del()">删除Person</button>
<script>
    //对象定义
    var person = {
        name: "DhL",
        age: 18,
        action: function (str) {
            var string = document.getElementById('str').value;
            if (string !== "") {
                document.getElementById("print").innerHTML = string;
            } else {
                document.getElementById("print").innerHTML = str;
            }
        }
    };


    function fun() {
        var txt = '';
        for (var x in person) {
            //! txt += x.value + " ";
            txt += person[x] + " ";
        }
        document.getElementById("print").innerHTML = txt;
    }


    function add() {
        //添加属性
        txt = '';
        person.favorite = 'running';
        for (var x in person) {
            //! txt += x.value + " ";
            txt += person[x] + " ";
        }
        document.getElementById("print").innerHTML = txt;
    }

    function del() {
        var txt = '';
        delete person.age;
        for (var x in person) {
            //! txt += x.value + " ";
            txt += person[x] + " ";
        }
        document.getElementById("print").innerHTML = txt
    }

    // 创建对象：
    var per = {
        firstName: "Bill",
        lastName: "Gates",
        language: "en",
        get lang() {
            return this.language;
        },
        set lang(lang) {
            this.language = lang;
        }
    };
    //Getter/Setter的访问形式:objectName.methodName，注意没有"()"
    per.lang = "Ch";
    document.getElementById("getset").innerHTML = per.lang;

    //使用构造器方式构造对象
    var persons = new Person("a", "Liu", 18, "big eye");
    var txt = '';
    for (x in persons) {
        txt += persons[x] + " ";
    }
    document.getElementById("construct").innerHTML = txt;

    var x=15;
    function f() {
        x=16;
        alert("x is :"+x);
    }
    f();
    document.getElementById("x").innerHTML = "x is "+x;
</script>

</body>
</html>